package com.codeoss.framework.report.query;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeoss.framework.util.IOUtil;
import com.codeoss.module.ir.model.IrReportQuery;
import com.codeoss.module.ir.service.IIrReportQueryService;

public class QueryDefBuilder {
	public static QueryDef build(String code,IIrReportQueryService irReportQueryService) {
		QueryWrapper<IrReportQuery> irQueryDefQuery = new QueryWrapper<IrReportQuery>();
		irQueryDefQuery.eq("code", code);
		IrReportQuery irReportQuery = irReportQueryService.getOne(irQueryDefQuery);
		String queryString = irReportQuery.getQueryDef();
		queryString="<query>"+queryString+"</query>";
		ByteArrayInputStream is = new ByteArrayInputStream(queryString.getBytes());
		DocumentBuilderFactory viewFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		try {
			builder = viewFactory.newDocumentBuilder();
			Document document = builder.parse(is);
			Element queryElement=(Element)document.getElementsByTagName("query").item(0);
			QueryDef queryDef=new QueryDef();
			queryDef.setCode(code);
			queryDef.setElement(queryElement);
			return queryDef;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}finally {
			IOUtil.closeInputStream(is);
		}
	}
}
